package com.zenika.training.wicket.zencontact;

import org.apache.wicket.Request;
import org.apache.wicket.Response;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zenika.training.wicket.zencontact.model.ContactDao;
import com.zenika.training.wicket.zencontact.pages.ListContactsPage;

public class ZenContactApplication extends WebApplication {

	public Class getHomePage() {
		return ListContactsPage.class;
	}

	private ApplicationContext getContext() {
		return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	}

	public static ContactDao getContactDao() {
		ZenContactApplication application = (ZenContactApplication) get();
		return (ContactDao) application.getContext().getBean("jdbcContactDao");
	}

	public static ZenContactApplication getApp() {
		return (ZenContactApplication) WebApplication.get();
	}

	public Session newSession(Request request, Response response) {
		return new ZenContactSession(request);
	}

	protected void init() {
		super.init();

		try {

			getContactDao().createDatabase();
		} catch (Exception e) {
			// expect an exception here if we try to create an existing table
			// and bury it.
		}
	}

}
